<template>
  <div>
    <!-- 头部面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色 -->
      <div>
        <el-button type="primary" @click="adddialogVisible=true">添加角色</el-button>
      </div>
      <!-- 列表 -->
      <el-table :data="RolesList" style="width: 100%" border>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-row
              v-for="(item1,index1) in props.row.children"
              :key="item1.id"
              :class="['bbtm',index1===0?'bbtp':'','itemCen']"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRight(item1.id,props.row)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级与三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                  :class="[index2===0?'':'bbtp','itemCen']"
                >
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRight(item2.id,props.row)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级 -->
                    <el-tag
                      closable
                      type="danger"
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      class="item3Tag"
                      @close="removeRight(item3.id,props.row)"
                    >{{item3.authName}}</el-tag>
                    <!-- <i class="el-icon-caret-right"></i> -->
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <!-- <div>{{scope.row.id}}</div> -->
            <el-button type="primary" icon="el-icon-edit">修改</el-button>
            <el-button type="danger" icon="el-icon-delete">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showrightdialogVisible(scope.row)"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="rightdialogVisible" width="30%" @close="CloseDialog">
      <!-- 树形控件 -->
      <el-tree
        :data="RightList"
        :props="rightProps"
        show-checkbox
        node-key="id"
        ref="RightTreeRef"
        default-expand-all
        :default-checked-keys="checkedRight"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AssignPermission">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="adddialogVisible" width="30%" @close="CloseAddDialog">
      <el-form ref="addFormRef" :model="addForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      RolesList: [],
      rightdialogVisible: false,
      RightList: [],
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      checkedRight: [],
      roleId: '',
      adddialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const res = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // this.$message.success(res.meta.msg)
      this.RolesList = res.data
    },
    // 移除权限
    async removeRight(rightId, role) {
      // 弹出提示框确认是否删除
      const result = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (result !== 'confirm') return this.$message.info('已取消删除')
      // console.log(rightId, role, result)
      // 确认删除，发送请求
      const res = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      // 删除失败
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 删除成功 重新渲染权限
      role.children = res.data
      // console.log(res)
    },
    // 分配角色 点击后让对话框显示
    async showrightdialogVisible(role) {
      // 保存角色id
      this.roleId = role.id
      // 获取所有权限信息
      const res = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 并将所有权限负责给数组
      this.RightList = res.data
      // 将已被选择的三级权限id以数组的形式保存起来
      this.getChild(role, this.checkedRight)
      this.rightdialogVisible = true
      console.log(res, 1)
    },
    getChild(node, arr) {
      // 如果没有children节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 有children节点的时候
      node.children.forEach(item => {
        return this.getChild(item, arr)
      })
    },
    CloseDialog() {
      // 当分配角色对话框关闭的时候，要将已选择的权限重新清空，只有在打开的时候才传递展示
      this.checkedRight = []
    },
    // 为用户分配权限
    async AssignPermission() {
      // 获取所有的选中与半选中状态的权限
      const Permission = [
        ...this.$refs.RightTreeRef.getCheckedKeys(),
        ...this.$refs.RightTreeRef.getHalfCheckedKeys()
      ]
      const ridsStr = Permission.join(',') // 以,号分割的字符串
      // console.log(ridsStr)
      // 发送请求
      const res = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: ridsStr
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 成功后,重新渲染角色列表
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.rightdialogVisible = false
    },
    // 取消添加角色
    CloseAddDialog() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加角色
    async addRole() {
      // 当点击确定，发送请求添加角色
      const res = await this.$http.post('roles', this.addForm)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.adddialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 10px 0;
}
.bbtm {
  border-bottom: 1px solid #eee;
}
.bbtp {
  border-top: 1px solid #eee;
}
.item3Tag {
  margin-right: 10px;
}
.itemCen {
  display: flex;
  align-items: center;
}
</style>
